package com.lagou.service.impl;

import com.lagou.dao.TokenDao;
import com.lagou.dao.UserDao;
import com.lagou.feign.CodeServiceFeignClient;
import com.lagou.pojo.ResultVO;
import com.lagou.pojo.TokenEntity;
import com.lagou.pojo.User;
import com.lagou.service.UserService;
import com.lagou.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;

/**
 * @author czq
 * @date 2020/9/15 16:37
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private CodeServiceFeignClient codeServiceFeignClient;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;

    @Override
    public ResultVO register(String email, String password, String code, HttpServletResponse response) {

        // 查看该邮箱是否已经注册过
        boolean isRegistered = isRegistered(email);
        if (isRegistered) {
            return ResultUtil.error("该邮箱已经注册过");
        }

        // 校验验证码
        int validate = codeServiceFeignClient.validate(email, code);
        if (validate == 1) {
            return ResultUtil.error("验证码错误");
        }
        if (validate == 2) {
            return ResultUtil.error("验证码超时");
        }

        // 注册
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        user.setCreatetime(new Date());
        userDao.save(user);

        // 生成令牌并保存到数据库中
        saveToken(email, response);

        return ResultUtil.success();
    }

    @Override
    public boolean isRegistered(String email) {
        User user = new User();
        user.setEmail(email);

        Example<User> example = Example.of(user);
        Optional<User> optional = userDao.findOne(example);
        if (optional.isEmpty()) {
            return false;
        }

        return true;
    }

    @Override
    public ResultVO loign(String email, String password, HttpServletResponse response) {

        User user = new User();
        user.setEmail(email);
        user.setPassword(password);

        Example<User> example = Example.of(user);
        Optional<User> optional = userDao.findOne(example);
        if (optional.isEmpty()) {
            return ResultUtil.error("邮箱或密码错误");
        }

        // 生成令牌并保存到数据库中
        saveToken(email, response);

        return ResultUtil.success(email);
    }

    @Override
    public ResultVO info(String token, HttpServletResponse response) {
        TokenEntity tokenEntity = new TokenEntity();
        tokenEntity.setToken(token);

        Example<TokenEntity> example = Example.of(tokenEntity);
        Optional<TokenEntity> optional = tokenDao.findOne(example);
        if (optional.isEmpty()) {
            ResultUtil.error("请重新登录");
        }

        return ResultUtil.success(optional.get().getEmail());
    }

    /**
     * 生成令牌并保存到数据库中
     */
    private void saveToken(String email, HttpServletResponse response) {

        // 判断是否已经存在旧的 token， 存在则替换，不存在则直接保存
        String token = UUID.randomUUID().toString().replace("-", "");
        TokenEntity tokenEntity = new TokenEntity();
        tokenEntity.setEmail(email);

        Example<TokenEntity> example = Example.of(tokenEntity);
        Optional<TokenEntity> optional = tokenDao.findOne(example);
        if (optional.isEmpty()) {
            tokenEntity.setToken(token);
            tokenDao.save(tokenEntity);
        } else {
            TokenEntity result = optional.get();
            result.setToken(token);
            tokenDao.save(result);
        }

        // 把令牌保存到保存到 cookie 中
        Cookie cookie = new Cookie("token", token);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
